package com.febers.ihealth.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager

/**
 * 参考： https://blog.csdn.net/RyomaFYx/article/details/84581655
 */
class LimitSlideDirectionViewPager : ViewPager {

    private var initialXValue: Float = 0.toFloat()
    private var direction: SwipeDirection? = null

    constructor(context: Context) : super(context) {
        this.direction = SwipeDirection.ALL
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        this.direction = SwipeDirection.ALL
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return if (this.isSwipeAllowed(event)) {
            super.onTouchEvent(event)
        } else false
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        return if (this.isSwipeAllowed(event)) {
            super.onInterceptTouchEvent(event)
        } else false
    }

    private fun isSwipeAllowed(event: MotionEvent): Boolean {
        if (this.direction === SwipeDirection.ALL) return true

        if (direction === SwipeDirection.NONE)
        //disable any swipe
            return false

        if (event.action == MotionEvent.ACTION_DOWN) {
            initialXValue = event.x
            return true
        }

        if (event.action == MotionEvent.ACTION_MOVE) {
            try {
                val diffX = event.x - initialXValue
                if (diffX > 0 && direction === SwipeDirection.RIGHT) {
                    // swipe from left to right detected
                    return false
                } else if (diffX < 0 && direction === SwipeDirection.LEFT) {
                    // swipe from right to left detected
                    return false
                }
            } catch (exception: Exception) {
                exception.printStackTrace()
            }
        }
        return true
    }

    fun setAllowedSwipeDirection(direction: SwipeDirection) {
        this.direction = direction
    }

    enum class SwipeDirection {
        ALL, RIGHT, LEFT, NONE
    }
}


